import axios from 'axios'
import {Toast} from 'vant'


// localhost 1.15.97.237
axios.defaults.baseURL = 'http://localhost:3000'
axios.defaults.withCredenttrue//跨域请求可以携带cookie


//响应拦截
axios.interceptors.response.use(res=>{
    if(typeof res.data !=='object'){
        Toast.fail('服务异常！')
        return Promise.reject(res)
    }
    if(res.data.code !=200){
        if(res.data.msg) Toast.fail(res.data.msg)
        if(res.data.code == 401){
            window.location.href = '/login'//登录国旗利用原生js的页面跳转到登录页面
        }
        console.log('res2');
        return Promise.reject(res.data)//让.catch()去获取错误
    }
    console.log('res');
    return res.data
},(error)=>{
    console.log(error);
    if(error.response.status >= 400 && error.response.status< 500){
        // window.location.href = '/login'
        console.log(error.response);
        console.log('status error');
    }
    return Promise.reject(error.response.data.error)
})


axios.interceptors.request.use((config) => {
    console.log('设置了token'); // 请求拦截之后就是要使用这个config, config表示整个请求对象
    config.headers.Authorization = localStorage.getItem('token'); // 将token从localStorage中取出并添加到请求头的Authorization字段上
    return config; // 返回请求对象，继续向服务器发起请求
}, err => {
    console.log('请求');
    return Promise.reject(err)
});


export default axios